package com.example.caijinglong.scanphoto

import android.Manifest
import android.media.MediaScannerConnection
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.content.ContentResolver
import android.content.pm.PackageManager
import android.os.Build
import android.support.v4.app.ActivityCompat
import android.util.Log
import android.content.Intent


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            ActivityCompat.requestPermissions(this, arrayOf<String>(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE), 3000)
        }
//        getPicFromP()
    }


    private fun getPicFromP() {
        //通过intent去找到本机中所有属性为image的文件；
        val intent = Intent()
        intent.type = "image/*"
        //ACTION_GET_CONTENT 允许用户选择特殊种类的数据，并返回，ACTION_Pick
        intent.action = Intent.ACTION_GET_CONTENT
        startActivityForResult(intent, 1)
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 3000) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                scan()
            }
        }
    }

    private val STORE_IMAGES = arrayOf(MediaStore.Images.Media.DISPLAY_NAME, // 显示的名字
            MediaStore.Images.Media.DATA, MediaStore.Images.Media.LONGITUDE, // 经度
            MediaStore.Images.Media._ID, // id
            MediaStore.Images.Media.BUCKET_ID, // dir id 目录
            MediaStore.Images.Media.BUCKET_DISPLAY_NAME // dir name 目录名字
    )


    var imgList = ArrayList<String>()

    fun scan() {
        Log.i("K", "start scan")
        val mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        val mContentResolver = this@MainActivity.contentResolver
        val mCursor = MediaStore.Images.Media.query(mContentResolver, mImageUri, STORE_IMAGES)
        //只查询jpeg的图片
//        val mCursor = mContentResolver.query(mImageUri, null,
//                MediaStore.Images.Media.MIME_TYPE + "=?",
//                arrayOf("image/jpeg"), MediaStore.Images.Media.DATE_TAKEN)ver

        //只查询jpeg的图片
//        val mCursor = mContentResolver.query(mImageUri, null,
//                null, null, null)

        val num = mCursor.count
        Log.i("K", "num = $num")
        while (mCursor.moveToNext()) {
            val path = mCursor.getString(mCursor
                    .getColumnIndex(MediaStore.Images.Media.DATA))
            imgList.add(path)
        }

        mCursor.close()
        print(imgList)
    }
}
